/**
 * @description 创建模板代码文件
 */
const templates = require('../template/index')
const chalk = require('chalk')
const inquirer = require('inquirer')
const fs = require('fs')
const utils = require('../utils/index')

function getFolder(path) {
  const components = []
  // 检查传入路径是否存在
  if (fs.existsSync(path)) {
    const files = fs.readdirSync(path)
    // console.log('files :>> ', files)
    files.forEach((item) => {
      const stat = fs.lstatSync(`${path}/${item}`)
      if (stat.isDirectory() === true && item !== 'components') {
        components.push(`${path}/${item}`)
        components.push(...getFolder(`${path}/${item}`))
      }
    })
  } else {
    console.log('组件目录不存在：', chalk.red('src/components is undefined'))
    process.exit() // node 退出进程
  }
  return components
}

module.exports = () => {
  inquirer
    .prompt([
      {
        name: 'templateName',
        type: 'list',
        message: '请选择你想要生成的代码模板：',
        choices: templates
      },
      {
        type: 'confirm',
        name: 'isGlobal',
        message: '是否为全局组件',
        default: false
      },
      {
        type: 'list',
        name: 'path',
        message: '请选择组件创建目录',
        choices: getFolder('src/components'),
        when: (answers) => {
          return !answers.isGlobal
        }
      },
      {
        name: 'filename',
        type: 'input',
        message: '请输入组件名称：',
        validate: function (value) {
          if (value.length) {
            return true
          } else {
            return '请输入组件名称名'
          }
        }
      }
    ])
    .then((answers) => {
      // console.log('answers :>> ', answers)
      const templateName = answers.templateName
      const filename = answers.filename
      templates.forEach((item) => {
        if (item.name === templateName) {
          const suffix = utils.getFileSuffix(item.name)
          const file = `${answers.path ? answers.path : '.'}/${filename}.vue`
          // 检验当前文件夹下是否有同名文件
          fs.access(file, function (err) {
            if (!err) {
              console.log('创建失败：', chalk.yellow('文件已存在'))
            } else {
              fs.writeFile(file, item.src(filename), function (err) {
                if (err) {
                  console.log('创建失败：', chalk.red(err))
                } else {
                  console.log(chalk.green(`创建文件成功！${file}`))
                }
              })
            }
          })
        }
      })
    })
}
